package com.cimp.util.iqy;

import org.apache.commons.net.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class CommonUtil {


    /**
     * token计算 一分钟内有效
     *
     * @return
     */
    public static String generateToken() {
        String src = IqyContants.MODEL_ID * IqyContants.PARTNER_ID + "i71";
        long t = System.currentTimeMillis();
        String secretkey = "i71" + t;
        String iv = 11717171 + "" + (IqyContants.MODEL_ID + 11717171);
        String token_0 = encrypt(src, secretkey, iv);
        String token = t + "" + token_0 + "_" + IqyContants.PARTNER_ID;
        return token;
    }


    private static String encrypt(String src, String secretkey, String iv) {
        byte[] encrypted = null;
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(secretkey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec ivP = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivP);
            encrypted = cipher.doFinal(src.getBytes());
        } catch (Exception e) {
            System.out.println("加密串生成失败！");
            return null;
        }
        try {
            return URLEncoder.encode(new String(Base64.encodeBase64(encrypted)), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.out.println("加密串生成失败！");
            return null;
        }
    }
}
